package com.example.elysiumease.controller;

import com.example.elysiumease.exception.BusinessException;
import com.example.elysiumease.mapper.UserMapper;
import com.example.elysiumease.model.User;
import com.example.elysiumease.result.ResponseResult;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotEmpty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/users")
@Validated
@Slf4j
public class UserController {

    //postman测试完成
    @Autowired
    private UserMapper userMapper;

    // 用户创建
    @PostMapping
    public ResponseResult<Integer> createUser(
            @Validated @RequestBody User user) {
        if (userMapper.insert(user) <= 0) {
            throw new BusinessException("用户创建失败");
        }
        return ResponseResult.success(user.getUserId());
    }

    // 角色分配（基于ENUM类型）
    @PutMapping("/{userId}/roles")
    @Transactional
    public ResponseResult<Void> assignRoles(
            @PathVariable @Min(1) Integer userId,
            @RequestBody @NotEmpty List<String> roles) {
        
        // 验证角色有效性
        if (roles.stream().anyMatch(role -> 
            !role.matches("ADMIN|JUDGE|OPERATOR"))) {
            throw new BusinessException("包含无效角色类型");
        }

        // 更新用户角色字段
        String roleStr = String.join(",", roles);
        if (userMapper.updateUserRole(userId, roleStr) <= 0) {
            throw new BusinessException("角色分配失败");
        }
        return ResponseResult.success();
    }

    // 用户信息查询
    @GetMapping("/{userId}")
    public ResponseResult<User> getUser(
            @PathVariable @Min(1) Integer userId) {
        User user = userMapper.selectById(userId);

        if (user == null) {
            throw new BusinessException(404, "用户不存在");
        }
        return ResponseResult.success(user);
    }

    // 用户信息更新
    @PutMapping("/{userId}")
    public ResponseResult<Void> updateUser(
            @PathVariable @Min(1) Integer userId,
            @Validated @RequestBody User user) {
        user.setUserId(userId);
        if (userMapper.update(user) <= 0) {
            throw new BusinessException("用户更新失败");
        }
        return ResponseResult.success();
    }

    // 用户删除
    @DeleteMapping("/{userId}")
    public ResponseResult<Void> deleteUser(
            @PathVariable @Min(1) Integer userId) {
        if (userMapper.deleteById(userId) <= 0) {
            throw new BusinessException("用户删除失败");
        }
        return ResponseResult.success();
    }
}